package com.swotxu.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swotxu.common.exception.NoStockException;
import com.swotxu.common.to.SkuHasStockTo;
import com.swotxu.common.utils.PageUtils;
import com.swotxu.common.utils.Query;
import com.swotxu.common.utils.R;
import com.swotxu.common.vo.SkuInfoVo;
import com.swotxu.mall.ware.dao.WareSkuDao;
import com.swotxu.mall.ware.entity.WareOrderTaskDetailEntity;
import com.swotxu.mall.ware.entity.WareOrderTaskEntity;
import com.swotxu.mall.ware.entity.WareSkuEntity;
import com.swotxu.mall.ware.feign.ProductFeignService;
import com.swotxu.mall.ware.service.WareOrderTaskService;
import com.swotxu.mall.ware.service.WareSkuService;
import com.swotxu.mall.ware.vo.OrderItemVo;
import com.swotxu.mall.ware.vo.WareSkuLockVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    WareSkuDao wareSkuDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSkuEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        String skuId = (String) params.get("skuId");
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(skuId), WareSkuEntity::getSkuId, skuId);

        String wareId = (String) params.get("wareId");
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(wareId), WareSkuEntity::getWareId, wareId);

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                lambdaQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer stock) {
        // 判断是否存在此库存记录，存在则更新，不存在则新增
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<WareSkuEntity>().eq(WareSkuEntity::getSkuId, skuId).eq(WareSkuEntity::getWareId, wareId));
        if (count > 0) {
            this.baseMapper.addStock(skuId, wareId, stock);
            return;
        }
        WareSkuEntity wareSkuEntity = new WareSkuEntity();
        wareSkuEntity.setSkuId(skuId);
        wareSkuEntity.setWareId(wareId);
        wareSkuEntity.setStock(stock);
        wareSkuEntity.setStockLocked(0);
        // 远程查询sku名字，若失败，整个事务无需回滚
        // 1、try吞掉异常
        // TODO 2、其他方式吞掉异常
        try {
            R result = productFeignService.skuInfo(skuId);
            if (result.isOk()) {
                SkuInfoVo data = result.getValue("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                wareSkuEntity.setSkuName(data.getSkuName());
            }
        } catch (Exception e) {
            log.warn("新增商品库存时，远程调用获取SKU_NAME异常！");
        }
        this.baseMapper.insert(wareSkuEntity);
    }

    @Override
    public List<SkuHasStockTo> getSkuHasStock(List<Long> skuIds) {
        // select sum(stock - stock_locked) from wms_ware_sku where sku_id in (16, 17) GROUP BY sku_id;
        List<WareSkuEntity> dataList = this.baseMapper.getSkuHasStock(skuIds);
        Map<Long, WareSkuEntity> skuEntityMap = dataList.stream().collect(Collectors.toMap(WareSkuEntity::getSkuId, Function.identity()));

        List<SkuHasStockTo> hasStockTos = skuIds.stream().map(skuId -> {
            SkuHasStockTo skuHasStockTo = new SkuHasStockTo();
            skuHasStockTo.setSkuId(skuId);
            skuHasStockTo.setHasStock(skuEntityMap.containsKey(skuId) && skuEntityMap.get(skuId).getStock() > 0);
            return skuHasStockTo;
        }).collect(Collectors.toList());

        return hasStockTos;
    }

    /**
     * 为某个订单锁定库存
     * <p>
     * (rollbackFor = NoStockException.class)
     * 默认只要是运行时异常都会回滚
     *
     * @param vo 库存解锁的场景
     *           1）、下订单成功，订单过期没有支付被系统自动取消、被用户手动取消。都要解锁库存
     *           <p>
     *           <p>
     *           2）、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。
     *           之前锁定的库存就要自动解锁。
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        // 保存库存工作单的详情。 - 追溯。
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        //1、按照下单的收货地址，找到一个就近仓库，锁定库存。
        //1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> hasStockList = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            stock.setSkuId(item.getSkuId());
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(item.getSkuId(), item.getCount());
            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(item.getSkuId());
            }
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock hasStock : hasStockList) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            //1、如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发给MQ
            //2、锁定失败。前面保存的工作单信息就回滚了。发送出去的消息，即使要解锁记录，由于去数据库查不到id，所以就不用解锁
            //     1： 1 - 2 - 1   2：2-1-2  3：3-1-1(x)
            for (Long wareId : hasStock.getWareId()) {
                //成功就返回1,否则就是0 ，若当前仓库锁失败，重试下一个仓库
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    skuStocked = true;
                    //TODO 告诉MQ库存锁定成功
//                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
//                    orderTaskDetailService.save(entity);
//                    StockLockedTo lockedTo = new StockLockedTo();
//                    lockedTo.setId(taskEntity.getId());
//                    StockDetailTo stockDetailTo = new StockDetailTo();
//                    BeanUtils.copyProperties(entity, stockDetailTo);
//                    //只发id不行，防止回滚以后找不到数据
//                    lockedTo.setDetail(stockDetailTo);
//                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                    break;
                }
            }
            if (!skuStocked) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        //3、肯定全部都是锁定成功过的
        return true;
    }


    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}